package com.mhkj.revise.monthPlan.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mhkj.common.enums.PlanSate;
import com.mhkj.revise.monthPlan.entity.Follow;
import com.mhkj.revise.monthPlan.service.PlanMonthAddService;
import com.mhkj.revise.monthPlan.service.PlanMonthService;
import com.mhkj.revise.plan.entity.PlanNode;
import com.mics.core.common.componet.JsonHandler;
import com.mics.core.common.componet.Pagination;
import com.mics.core.common.componet.ResponseMessage;
import com.mics.core.common.util.UserHelper;
import com.mics.core.system.base.controller.BaseController;
import com.mics.core.system.organizational.bean.Post;
import com.mics.core.system.organizational.service.OrgService;

@Controller
@RequestMapping("/monthformation")
public class PlanMonthController extends BaseController<PlanNode> {
    @Resource
    private PlanMonthService planMonthService;
    @Resource
    PlanMonthAddService planMonthAddService;
    @Resource
    private JsonHandler jsonHandler;
    @Resource
    private OrgService orgService;
    
    @RequestMapping("/keyListByPage")
    @ResponseBody
    public void keyListByPage(HttpServletResponse response, PlanNode planNode, String yearMonth,String nodeName,String dateTemp, int pageIndex, int pageSize) throws ParseException {
        String firstDay=null;
        String lastDay=null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if(yearMonth==null) {
            //获取本月
            Calendar cal_1=Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, 0);
            cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            firstDay = format.format(cal_1.getTime());
            //获取结束月份
            Calendar cale = Calendar.getInstance();
            if(cale.get(Calendar.DATE)>=20) {//大于20号 需要查询下月
                cale.add(Calendar.MONTH, 1);
            }else {
                cale.add(Calendar.MONTH, 0);
            }
            cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
            lastDay = format.format(cale.getTime());
        }else {
            Date formattime = new SimpleDateFormat("yyyy-MM").parse(yearMonth);
            firstDay=format.format(formattime.getTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(formattime);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
            lastDay=format.format(calendar.getTime());
        }

        Pagination<PlanNode> pagination = planMonthService.keyListByPage(planNode,yearMonth,firstDay,lastDay,nodeName,dateTemp,1, pageIndex, pageSize);
        List<PlanNode> planNodes = pagination.getData();
        String employeeId = UserHelper.getCurrentUserId();
        List<Follow> follows = planMonthAddService.getByEmployeeId(employeeId);
        for(PlanNode planNodeTemp : planNodes){
            if(follows != null && follows.size() > 0){
                for(Follow follow:follows){
                    if(follow.getPlanNode().getId() == planNodeTemp.getId()){
                        planNodeTemp.setCare(1);
                        String copanyname = orgService.getCompanyById(planNodeTemp.getCompanyId()).getCompanyname();
                        planNodeTemp.setCompanyName(copanyname);
                        String officeName = orgService.officeInfo(planNodeTemp.getOfficeId()).getName();
                        planNodeTemp.setOfficeName(officeName);
                        Post post = orgService.getRoleInfo(planNodeTemp.getPostId());
                        planNodeTemp.setPostName(post.getName());
                    }
                }
            }
        }
        jsonHandler.sendJsonString(response, true, "获取数据成功", pagination,new String[]{
                "id","nodeName","plan.name","beginDate","endDate","createDate","nodeProperty.value","care","companyName","officeName","postName"},
                "id","nodeName","remindFrequencyName","beginDate","endDate","createDate","value","care","companyName","officeName","postName");
    }


    @RequestMapping(value="/follow", method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage add( PlanNode planNode) {
        Follow follow = new Follow();
        Long planNodeId = planNode.getId();
        String employeeId = UserHelper.getCurrentUserId();
        List<Follow> follows = planMonthAddService.getplanNodeId(planNodeId,employeeId);
        List<String> v = new ArrayList<String>();

        if(follows.size()==0){
            String userId = UserHelper.getCurrentUserId();
            follow.setPlanNode(planNode);
            follow.setEmployeeId(userId);
            String message = planMonthAddService.save(follow);
           // v.add("true");
            return ResponseMessage.createMessage("ok".equals(message), message);
        }else{
            //已经存在返回false
            String false1 = null;
           //v.add("false");
            String message ="exist";
            return ResponseMessage.createMessage("ok".equals(message), message);

          //  return ResponseMessage.createMessage("ok",equals());
        }

    }


    @RequestMapping(value="/cancelFollow", method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage cancelFollow(long planNodeId) {
        String userId = UserHelper.getCurrentUserId();
        Follow follow = planMonthAddService.getByUserAndPlanId(userId,planNodeId);
        String message = planMonthAddService.del(follow);
        return ResponseMessage.createMessage("ok".equals(message), message);

    }

    @RequestMapping(value="/stat")
    @ResponseBody
    public void stat(HttpServletResponse response){
        String employeeId = UserHelper.getCurrentUserId();
        List<Follow> follows = planMonthAddService.getByEmployeeId(employeeId);
        int allFollow = follows.size();
        int runawayNumber = 0;
        int runningNumber = 0;
        int overNumber = 0;
        int riskNumber = 0;
        for(Follow follow : follows){
            PlanNode planNode = planMonthService.getById(follow.getPlanNode().getId());
            if(planNode.getRiskState() == 2 ){ //失控
                runawayNumber++;
            }else if(planNode.getRiskState() == 1){//有风险
                riskNumber++;
            }
            //2
            if(planNode.getState() == PlanSate.running.getState() && planNode.getRiskState() == 0 ){
                runningNumber++;
                //7
            }else if(planNode.getState()==PlanSate.overdue.getState() && planNode.getRiskState() != 2 ){
                overNumber++;
            }
        }

        jsonHandler.sendJsonContent(response, true, "获取数据成功", new Object[]{
                "allFollow",allFollow,"runawayNumber",runawayNumber,"runningNumber",runningNumber,"overNumber",overNumber,"riskNumber",riskNumber});
    }

}
